import socket
import struct
import time

import connection
import io

class NetworkServer:
	def __init__(self, homeswitch, discover_port):
		self.homeswitch = homeswitch
		self.discover_port = discover_port
		
		self.io = io.get_default_io()
		
		self.discovery = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		self.discovery.bind(('<broadcast>', self.discover_port))
		self.io.register(io.Proxy(self.discovery, self.on_discovery_connect), io.POLLIN)
		print "Listening on UDP port %d" % self.discovery.getsockname()[1]
		
		self.receiver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		self.receiver.listen(10)
		self.io.register(io.Proxy(self.receiver, self.on_receiver_connect), io.POLLIN)
		print "Listening on TCP port %d" % self.receiver.getsockname()[1]
	
	def on_discovery_connect(self, state):
		msg, (addr, port) = self.discovery.recvfrom(8)
		target_port = struct.unpack('!I', msg)[0]
		
		print "got call from %s:%d, will answer to :%d, I'm at :%d" % (addr, port, target_port, self.receiver.getsockname()[1])
		
		r = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		r.connect((addr, target_port))
		
		r.send(struct.pack("!H", self.receiver.getsockname()[1]))
		r.close()
	
	def on_receiver_connect(self, state):
		conn, addr = self.receiver.accept()
		print "got connection from %s:%d" % addr
		connection.Connection(self.homeswitch, conn, addr)
	

